package com.usiful.controller;

import java.util.ArrayList;
import java.util.List;

import com.usiful.model.ActionArg;
import com.usiful.utils.FileUtil;
import com.usiful.utils.PathUtil;
import com.usiful.utils.ShellUtil;

/**
 * 应用签名控制器[目前只支持gradle构建输出的目录结构]
 * @author [周织能]
 *
 */
public class SignController extends BaseController{

	public final static String ARG_PROJECT_PATH = "path";
	public final static String ARG_KEYSTORE = "keystore";
	public final static String ARG_ALIAS = "alias";
	public final static String ARG_KEYPASS = "keypass";
	public final static String ARG_STOREPASS = "aliaspass";
	public final static String ARG_SIGN_APKDIR = "apkdir";
	protected String mProjectPath;
	
	@Override
	public boolean handleAction(ActionArg arg) {
		// TODO Auto-generated method stub
		super.handleAction(arg);
		mProjectPath = arg.getArgValueMap().get(ARG_PROJECT_PATH).get(0);
		String keystore = arg.getArgValueMap().get(ARG_KEYSTORE).get(0);
		String alias = arg.getArgValueMap().get(ARG_ALIAS).get(0);
		String keypass = arg.getArgValueMap().get(ARG_KEYPASS).get(0);
		String storepass = arg.getArgValueMap().get(ARG_STOREPASS).get(0);
		String sigApkDir = arg.getArgValueMap().get(ARG_SIGN_APKDIR).get(0);
		if(sinatureApk(mProjectPath,keystore,alias,keypass,storepass,sigApkDir)) {
			System.out.println("apk签名成功!");
			return true;
		} else {
			System.out.println("apk签名失败!");
			return false;
		}
	}

	/**
	 * 为apk签名,只签release的包
	 * @param projectPath
	 * @param keystore
	 * @param alias
	 * @param keypass
	 * @param apkdir
	 */
	private boolean sinatureApk(String projectPath,String keystore,String alias,String keypass,String storepass,String sigApkdir) {
		Boolean sigResult = true;
		String apkDir = PathUtil.getFullPath(mProjectPath,"build","outputs","apk");
		List<String> files = new ArrayList<String>();
		FileUtil.getFiles(apkDir,files);
		String unsigApkFile = null;
		for(String file : files) {
			if(file.contains(".apk") && file.contains("release")) {
				unsigApkFile = file;
				break;
			}
		}
		if(unsigApkFile == null) {
			return false;
		}
		String cmd = "jarsigner";
		String[] cmdArgs = {
				"-verbose -keystore ",keystore,
				"-keypass",keypass,"-storepass",
				storepass,"-signedjar",PathUtil.getFullPath(sigApkdir,"app.apk"),
				unsigApkFile,alias, "-digestalg SHA1 -sigalg MD5withRSA"
		};
		try {
			sigResult = ShellUtil.exec(cmd, cmdArgs).errcode == ShellUtil.SHELL_EXEC_SUCC ? true : false;
		} catch (Exception e) {
			sigResult = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sigResult;
	}
	
}
